﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using DICE_GS;
using System.Linq;

[System.Serializable]
public class CharInfo
{
    public int hp;
    public int mp;
    public int maxHp;
    public int maxMp;

    public bool isDead;
    public int hpChange;
    public int hpToBe;
    public float hpFillAmount;
    public bool isShowHPChageEffect;
}

[System.Serializable]
public class HPChangeInfo
{
    public int sid;
    public BoardPerson person;
    public HPModReason reason;
    public int before;
    public int delta;
    public int after;
    public bool isApplied;
    public int boardId;

    public HPChangeInfo(int _sid, BoardPerson _person, HPModReason _reason, int _before, int _delta, int _after, int bid)
    {
        Init(_sid, _person, _reason, _before, _delta, _after, bid);
    }

    public void Init(int _sid, BoardPerson _person, HPModReason _reason, int _before, int _delta, int _after, int bid)
    {
        sid = _sid;
        person = _person;
        reason = _reason;
        before = _before;
        delta = _delta;
        after = _after;
        boardId = bid;
        isApplied = false;
    }

    public bool IsBattleReason()
    {
        if (reason == HPModReason.COMBAT_WITH_NPC || reason == HPModReason.COMBAT_WITH_NPC_REFLECTION || reason == HPModReason.COMBAT_WITH_RUNNER || reason == HPModReason.COMBAT_WITH_RUNNER_REFLECTION)
            return true;
        return false;
    }

    public bool IsAvoidDeath()
    {
        if (reason == HPModReason.AVOID_DEATH)
            return true;
        return false;
    }
}

[System.Serializable]
public class MPChangeInfo
{
    public int sid;
    public BoardPerson person;
    public MPRegenType reason;
    public int before;
    public int delta;
    public int after;
    public bool isApplied;
    public int boardId;

    public MPChangeInfo(int _sid, BoardPerson _person, MPRegenType _reason, int _before, int _delta, int _after, int bid)
    {
        Init(_sid, _person, _reason, _before, _delta, _after, bid);
    }

    public void Init(int _sid, BoardPerson _person, MPRegenType _reason, int _before, int _delta, int _after, int bid)
    {
        sid = _sid;
        person = _person;
        reason = _reason;
        before = _before;
        delta = _delta;
        after = _after;
        boardId = bid;
        isApplied = false;
    }
}

public class HudManager : MonoBehaviour
{

    private static HudManager instance;

    public static HudManager Instance
    {
        get
        {
            return instance;
        }
    }

    void Awake()
    {
        instance = this;

        hpHealText = CStringTableManager.Instance.GetItemById(1710);
        hpDamageText = CStringTableManager.Instance.GetItemById(1709);

    }
    string hpHealText;
    string hpDamageText;
    public GameObject hpChangePrefab;
    public GameObject[] charPanel;
    public float charPanelScaleMod;
    Dictionary<int, GameObject> sidPanelDic = new Dictionary<int, GameObject>();
    Dictionary<int, CharacterPanel> sidCharacterPanelDic = new Dictionary<int, CharacterPanel>();
    Dictionary<int, GameObject> sidBufPanelDic = new Dictionary<int, GameObject>();
    public Dictionary<int, List<BuffIcon>> sidBufIconsDic = new Dictionary<int, List<BuffIcon>>();
    public Dictionary<int, int> charOrderSidDic = new Dictionary<int, int>();
    public Dictionary<int, int> charSidOrderDic = new Dictionary<int, int>();
    public Dictionary<int, string> charSidSpriteNameDic = new Dictionary<int, string>();
    public Dictionary<int, float> timeChangingFace = new Dictionary<int, float>();
    Dictionary<int, CharInfo> charInfoDic = new Dictionary<int, CharInfo>();

    public Transform[] charPanelPos;
    public GameObject[] charPanelParent;
    public GameObject charPanelPrefab;
    public GameObject replayLabel;
    public GameObject ingameTag;
    //public GrayscaleEffect grayEffect;
    UIRoot uiroot;
    static GameObject buffPanelPrefab;
    static GameObject buffIconPrefab;
    List<BuffIcon> tempBufIconList = new List<BuffIcon>();
    public List<HPChangeInfo> hpChangeInfo = new List<HPChangeInfo>();
    public List<MPChangeInfo> mpChangeInfo = new List<MPChangeInfo>();
    static HitDamageNum hpDamageNumPrefab;
    static ChanceSkill chanceSkillPrefab;

    void Start()
    {
        if (CSceneManager.isReplay)
            replayLabel.SetActive(true);

        uiroot = GameObject.Find("UI Root (2D)").GetComponent<UIRoot>();
        if (uiroot != null)
        {
            Camera cam = uiroot.GetComponentInChildren<Camera>();
            if (cam != null)
            {
                //	grayEffect = cam.GetComponent<GrayscaleEffect>();
            }
        }
        GameObject hpDamageNumPrefabGo = Resources.Load("Prefabs/FX/FX_HitDamageNum") as GameObject;
        if (hpDamageNumPrefabGo != null)
        {
            hpDamageNumPrefab = hpDamageNumPrefabGo.GetComponent<HitDamageNum>();
            if (hpDamageNumPrefab != null)
                ObjectPool.CreatePool(hpDamageNumPrefab);
        }

        GameObject tmpGo = Resources.Load("Prefabs/FX/ChanceSkill") as GameObject;
        if (tmpGo != null)
        {
            chanceSkillPrefab = tmpGo.GetComponent<ChanceSkill>();
            if (chanceSkillPrefab != null)
                ObjectPool.CreatePool(chanceSkillPrefab);
        }
    }

    public bool IsLocalKorean()
    {
        return true;
    }

	public void SetRetiredPanelGray(int sid, bool bActivate)
	{
		if (!sidPanelDic.ContainsKey(sid))
			return;
		if(bActivate)
			sidPanelDic[sid].GetComponent<MultiplySpriteColorChildren>().SetToGray();
		else
			sidPanelDic[sid].GetComponent<MultiplySpriteColorChildren>().BackToOriginal();
	}

    public void MakePanelAdvance(int i)
    {
        if (charPanelPrefab == null)
            charPanelPrefab = Resources.Load("Prefabs/UI/Panel_Char_new") as GameObject;
        charPanel[i] = NGUITools.AddChild(charPanelParent[i], charPanelPrefab);
        charPanel[i].GetComponent<UIPanel>().depth = 20 + i;
        charPanel[i].transform.localPosition = charPanelPos[i].localPosition;
        charPanel[i].transform.localRotation = charPanelPos[i].localRotation;
        charPanel[i].transform.localScale = charPanelPos[i].localScale;
		charPanel[i].AddComponent<MultiplySpriteColorChildren>();
        charPanel[i].SetActive(false);
    }

    void MakeBufPanel(int sid, int i)
    {
        //if (buffPanelPrefab == null)
       //     buffPanelPrefab = Resources.Load("Prefabs/UI/BuffPanel") as GameObject;
		GameObject bufpanel = charPanel[i].transform.FindChild("BuffPanel").gameObject;//NGUITools.AddChild(charPanel[i], buffPanelPrefab);
		if(i==3 || i==4)
			bufpanel.transform.localScale = new Vector3(-1,1,1);
//        if (i == 1 || i == 4)
//            bufpanel.transform.localPosition = new Vector3(79, 259, 0);
//        else
//            bufpanel.transform.localPosition = new Vector3(50, -50, 0);
        sidBufPanelDic.Add(sid, bufpanel);
        sidBufIconsDic.Add(sid, new List<BuffIcon>());
    }
    //isBoss = false
    public void InitPanel(int sid, int nOrder, int nLevel, string nickName, int charID, bool isBoss, bool is2PlayerOnly, GAME_PAWN_TYPE pawnType)
    {       
        charOrderSidDic.Add(nOrder, sid);
        charSidOrderDic.Add(sid, nOrder);
        timeChangingFace.Add(sid, 0);
        if (charPanel[nOrder] == null)
            MakePanelAdvance(nOrder);
        charPanel[nOrder].SetActive(true);
        MakeBufPanel(sid, nOrder);
        sidPanelDic.Add(sid, charPanel[nOrder]);
        // 케릭터 패널 추가 및 패널 SID 설정
        CharacterPanel tempCP = charPanel[nOrder].GetComponent<CharacterPanel>();
        tempCP.SID = sid;
        tempCP.Order = nOrder;
        sidCharacterPanelDic.Add(sid, tempCP);

        string str = String.Format("NO_Portrait__{0:0}", nOrder);
        //if(isBoss)
        //    str = String.Format("IngameUi_text_{0:0}p_yellow",nOrder-1);
        //if(is2PlayerOnly)
        //    str = String.Format("IngameUi_text_{0:0}p_yellow",nOrder-1);       
        UISprite obj1p = tempCP.m_1P;
        obj1p.gameObject.SetActive(true);
        obj1p.spriteName = str;//8~11
        FlipObject(nOrder, obj1p.gameObject);
        if (!isBoss)
            obj1p.gameObject.SetActive(false);
        SetUserNameAndLevel(sid, nOrder, nickName, nLevel);

        //GameObject charObject = GetPanelCharChild(sid, "Char");
        GameObject charObject = GetCharacterPanel(sid).m_Char.gameObject;

        charObject.SetActive(true);
        if (isBoss)
        {
            string sprName = String.Format("IngameUi_cha_b1");
            //charSidSpriteNameDic.Add( sid, sprName);
            charObject.GetComponent<UISprite>().spriteName = sprName;
        }
        else
        {
            string sprName = String.Format("IngameUi_cha{0:00}", charID);
            charSidSpriteNameDic.Add(sid, sprName);
            charObject.GetComponent<UISprite>().spriteName = sprName;
        }
        charObject.GetComponent<UIPressCharImage>().charOrder = nOrder;
        //Color circleColor = IngameSetting.Instance.p_color[nOrder-1];
        //if(!isBoss)
        //    circleColor.a = 0;
        tempCP.m_CharFrame.gameObject.SetActive(true);       
        tempCP.m_CharFrame.spriteName = string.Format("Portrait_{0}", IngameSetting.CharColorName[nOrder - 1]);

        SetPanel_CharColor(sid, nOrder - 1);

        if (nOrder >= 2)
            charPanelScaleMod = 1 / charPanel[nOrder].transform.localScale.x;

        //PlayGear(sid);
        //StartCoroutine( CoPauseGear(sid) );
        if (pawnType == GAME_PAWN_TYPE.BOT)
            SetBotMark(sid, true);
    }


    public void ChangeByGameOrder(int gameOrder, int createOrder)
    {
        BoardPerson person = null;
        foreach (BoardPerson p in BoardManager.Instance.boardPersonPCList)
        {
            if (p.gameOrder == gameOrder)
            {
                person = p;
                break;
            }
        }
        int sid = person.SID;
        glog.debug(sid + " ChangeByGameOrder " + gameOrder);
        // determine 1p,2p,3p,4p by gameorder


        if (!person.isMe)
        {
            bool is2PlayerOnly = false;
            MainHUDUI.Instance.SetPlayerTagStart(createOrder - 1, person.isBoss);
            if (createOrder == 2 && BoardManager.Instance.runnerCnt == 2)
            {
                is2PlayerOnly = true;
                createOrder = 3;
            }
            person.order = createOrder;
            InitPanel(sid, createOrder, person.nLevel, person.nickName, person.charID, person.isBoss, is2PlayerOnly, person.pawnType);
            CardManager.Instance.CreateTeamCards(person);
        }

        StageManagerWrapper.MakeGroundTag(person, createOrder);

        if (person.isBoss)
            return;

        string strP = String.Format("NO_Portrait__{0:0}", gameOrder);

        CharacterPanel char_Panel = GetCharacterPanel(sid);
        UISprite obj1p = char_Panel.m_1P;
        obj1p.gameObject.SetActive(true);
        obj1p.spriteName = strP;
        char_Panel.m_CharFrame.spriteName = string.Format("Portrait_{0}", IngameSetting.CharColorName[gameOrder - 1]);        
        person.groundTag.GetComponent<ParticleSystem>().startColor = IngameSetting.Instance.p_color[gameOrder - 1];
        SetPanel_CharColor(sid, gameOrder - 1);
        //person.SetGameOrder(gameOrder);

        // 머리위에 떠있는 순서 설정
        strP = String.Format("IngameUi_text_{0:0}p", gameOrder);
        person.tagOverHead = Instantiate(ingameTag) as GameObject;
        person.tagOverHead.transform.parent = person.transform;
        person.tagOverHead.GetComponent<tk2dSprite>().SetSprite(strP);
        person.tagOverHead.transform.localPosition = new Vector3(0, person.overHeadNameTagOffset, 0);

        ////나일때만 이모티콘 버튼 출력       
        char_Panel.m_EmoticonBtn.SetActive(person.isMe);
    }

    public void SetPanel_CharColor(int sid, int colorIndex)
    {
        GetCharacterPanel(sid).SetPlayerColor(colorIndex);
    }

    public void RearrangeBufIcon(int sid)
    {
        if (!sidBufPanelDic.ContainsKey(sid))
            return;
        var list = sidBufIconsDic[sid];
        int listActiveCount = 0;
        foreach (BuffIcon icon in list)
        {
            if (icon.isActive)
                listActiveCount++;
        }

        tempBufIconList.Clear();
        bool bArrangeNeeded = false;
        foreach (BuffIcon icon in list)
        {
            if (icon.isActive)
            {
                if (icon.index >= listActiveCount)
                    bArrangeNeeded = true;
                tempBufIconList.Add(icon);
            }
        }
        if (bArrangeNeeded)
        {
            tempBufIconList.Sort(
                delegate(BuffIcon p1, BuffIcon p2)
                {
                    return p1.index.CompareTo(p2.index);
                }
            );
            int index = 0;
            foreach (BuffIcon icon in tempBufIconList)
            {
                icon.index = index;
                icon.SetPosition();
                index++;
            }
        }
    }

    string GetBuffIcon(AbnormalType abnormalType, int abnormalParam)
    {
        if (abnormalType == AbnormalType.BIND)
            return "icon_skill_bind";
        else if (abnormalType == AbnormalType.SLEEP)
            return "icon_skill_sleep";
        else if (abnormalType == AbnormalType.SEAL_ACTIVE_CARD_SLOT)
            return "icon_skill_seal_card";
        else if (abnormalType == AbnormalType.MODIFY_MOVE_COST)
            return "icon_skill_bumpy";
        else if (abnormalType == AbnormalType.MOVE_DIRECTION && abnormalParam == (int)MoveDirection.backward)
            return "icon_skill_back";
        else if (abnormalType == AbnormalType.MOVE_DIRECTION && abnormalParam == (int)MoveDirection.random)
            return "icon_skill_random";
        else if (abnormalType == AbnormalType.ELEMENT_CHANGE && abnormalParam == (int)element.absolute)
            return "icon_skill_card_con";
        else if (abnormalType == AbnormalType.ELEMENT_CHANGE && abnormalParam == (int)element.inferior)
            return "icon_skill_tomb";
        else if (abnormalType == AbnormalType.TRANSFER_PARAM && abnormalParam == (int)TransferType.attack)
            return "icon_skill_trans_attack";
        else if (abnormalType == AbnormalType.TRANSFER_PARAM && abnormalParam == (int)TransferType.move)
            return "icon_skill_trans_move";
        else if (abnormalType == AbnormalType.TRANSFER_PARAM && abnormalParam == (int)TransferType.defense)
            return "icon_skill_trans_defense";
        else if (abnormalType == AbnormalType.MODIFY_BLOCK)
            return "icon_skill_block";
        else if (abnormalType == AbnormalType.MODIFY_AVOID)
            return "icon_skill_avoid";
        else if (abnormalType == AbnormalType.MODIFY_MOVE)
            return "icon_skill_move";
        else if (abnormalType == AbnormalType.MODIFY_CHASE)
            return "icon_skill_chase";
        else if (abnormalType == AbnormalType.DAMAGE_REDUCE)
            return "icon_skill_dmg_reduce";
        else if (abnormalType == AbnormalType.PUSHBACK_RESIST)
            return "icon_skill_block";
        return "";
    }

    string GetBuffIcon(int skillId)
    {
        CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
        if (skillData != null)
        {
            return skillData.icon_name;
        }
        return "";
    }

    public void ShowBuffIcon(bool show, int sid, AbnormalType abnormalType, int abnormalParam, int relatedSkillId)
    {
        if (!sidBufPanelDic.ContainsKey(sid))
            return;
        if (!show)
            SkillManager.Instance.RemoveSkillEffect(sid, abnormalType, abnormalParam);
        string iconName = GetBuffIcon(relatedSkillId);
        if (show && String.IsNullOrEmpty(iconName))
            return;
        if (show)
        {
            var list = sidBufIconsDic[sid];
            BuffIcon iconPooled = null;
            int listActiveCount = 0;
            foreach (BuffIcon icon in list)
            {
                if (icon.IsSameAbnormal(abnormalType, abnormalParam))
                {
                    return;
                }
                if (!icon.isActive && iconPooled == null)
                    iconPooled = icon;
                if (icon.isActive)
                    listActiveCount++;
            }
            if (iconPooled != null)
                iconPooled.Activate(abnormalType, abnormalParam, listActiveCount, iconName);
            else
            {
                if (buffIconPrefab == null)
                    buffIconPrefab = Resources.Load("Prefabs/UI/buffIcon") as GameObject;
                GameObject newBufIcon = NGUITools.AddChild(sidBufPanelDic[sid], buffIconPrefab);
                newBufIcon.transform.localScale = new Vector3(0.3f, 0.3f, 1);
                BuffIcon newBuffIconScript = newBufIcon.GetComponent<BuffIcon>();
                newBuffIconScript.Init(abnormalType, abnormalParam, listActiveCount, iconName);
                list.Add(newBuffIconScript);
            }
        }
        else
        {
            var list = sidBufIconsDic[sid];
            foreach (BuffIcon icon in list)
            {
                if (icon.IsSameAbnormal(abnormalType, abnormalParam))
                {
                    icon.GotoPool();
                    break;
                }
            }
        }

    }

    //	IEnumerator CoPauseGear(int sid)
    //	{
    //		yield return new WaitForSeconds(0.01f);
    //		PauseGear(sid);
    //	}

    public void ChangeFace(int sid, bool bWin)
    {
        if (!sidPanelDic.ContainsKey(sid))
            return;
        if (!charSidSpriteNameDic.ContainsKey(sid))
            return;
        StartCoroutine(CoChangeFace(sid, bWin));
    }

    IEnumerator CoChangeFace(int sid, bool bWin)
    {
        string postFix = "_lose";
        if (bWin)
            postFix = "_win";
        timeChangingFace[sid] = Time.time;

        
        //GetPanelCharChild(sid, "Char").GetComponent<UISprite>().spriteName = charSidSpriteNameDic[sid] + postFix;

        GetCharacterPanel(sid).ChangeFace(charSidSpriteNameDic[sid] + postFix);
        yield return new WaitForSeconds(1.5f);
        if (Time.time - timeChangingFace[sid] > 1.4f)
        {
            //GetPanelCharChild(sid, "Char").GetComponent<UISprite>().spriteName = charSidSpriteNameDic[sid];

            GetCharacterPanel(sid).ChangeFace(charSidSpriteNameDic[sid]);
        }
    }

    //public GameObject GetPanelCharChild(int sid, string name)
    //{
    //    return GetPanelChild(sid, "Panel_char").transform.FindChild(name).gameObject;
    //}

    bool IsMirrorPanel(int order)
    {
        if (order == 3 || order == 4)
            return true;
        return false;
    }

    void FlipObject(int order, GameObject go)
    {
        if (IsMirrorPanel(order))
        {
            Vector3 scale = go.transform.localScale;
            scale.x = -scale.x;
            go.transform.localScale = scale;
        }

    }

    void SetUserNameAndLevel(int sid, int order, string userName, int level)
    {
        CharacterPanel char_panel = GetCharacterPanel(sid);

        Transform child = char_panel.m_FlipRoot.transform;            

        child.gameObject.SetActive(true);
        FlipObject(order, child.gameObject);


        Transform target = char_panel.m_UserName.transform;
        char_panel.m_UserName.text = userName;

        target = char_panel.m_LevelNum.transform;
        char_panel.m_LevelNum.text = level.ToString();

        FlipObject(order, char_panel.m_Panel_gage);
        FlipObject(order, char_panel.m_BotLabel.gameObject);
    }

    //void SetUserLevel(int sid, int order, int level)
    //{
    //foreach( Transform child in GetPanelChild(sid,"Panel_char").transform)
    //{
    //    if (child.gameObject.name == "Level_Num" || child.gameObject.name == "Bot" || child.gameObject.name == "Lap" || child.gameObject.name == "HPDetail")
    //    {
    //        //glog.debug("set level "+level);
    //        if (child.gameObject.name == "Level_Num")
    //        {
    //            child.gameObject.SetActive(true);
    //            child.gameObject.GetComponent<UILabel>().text = level.ToString();
    //        }
    //        if(child.gameObject.name == "Lap")
    //        {
    //            foreach( Transform lapchild in child.gameObject.transform)
    //            {
    //                FlipObject(order, lapchild.gameObject);
    //            }
    //        }
    //        else
    //            FlipObject(order, child.gameObject);
    //    }
    //}
    //}	

    public void SetBotMark(int sid, bool show)
    {       
        GetCharacterPanel(sid).m_BotLabel.gameObject.SetActive(show);
        //만약 내가 봇이 될경우 카운트 제거
        SetTurnTimeCount(sid, false);
    }


    public void SetTurnTimeCount(int sid, bool show)
    {
		if (!sidPanelDic.ContainsKey(sid))
			return;

		//StartCoroutine("CoSetTurnTimeCount");

        CharacterPanel char_panel = GetCharacterPanel(sid);

		//gage.gameObject.SetActive (show);
        char_panel.m_RemainTimeLabel.gameObject.SetActive(show);
        char_panel.m_1P.gameObject.SetActive(!show);

        if (!show)
        {
            m_GageSp = null;           
            char_panel.m_Gage.fillAmount = 1.0f;
        }
    }

//	IEnumerator CoSetTurnTimeCount()
//	{
//
//	}
    float m_GageTimer = 0;
    UISprite m_GageSp = null;
    public void SetTrunTimeCountNum(int sid, float time, bool isNeedAni)
    {
        if(isNeedAni)
            m_GageTimer = (float)time;

        CharacterPanel char_panel = GetCharacterPanel(sid);
        
        char_panel.m_RemainTimeLabel.text = ((int)time).ToString();

        if (m_GageSp == null)
        {
            m_GageSp = char_panel.m_Gage;
        }
    }


    void Update()
    {
        if (m_GageTimer > 0 && m_GageSp != null)
        {
            m_GageTimer -= Time.deltaTime;
            m_GageSp.fillAmount = m_GageTimer / 30.0f;
        }
    }



    public void SetLapCount(int sid, int lapcount)
    {       
        lapcount = 3 - lapcount;

        if (BoardManager.Instance.curMapRaceType == RaceType.CURCUIT_RACE)
        {
            CharacterPanel char_panel = GetCharacterPanel(sid);
          
            for (int i = 0; i < 2; i++)
            {              
                char_panel.m_ArrowOff[i].gameObject.SetActive(lapcount > i + 1);
            }

            for (int i = 0; i < 3; i++)
            {
                char_panel.m_On[i].gameObject.SetActive(lapcount > i);                
            }
        }
    }

    //GameObject GetPanelGearChild(int sid, string name)
    //{
    //    return GetPanelChild(sid, "Panel_gage").transform.FindChild(name).gameObject;
    //}

    //public void PauseGear(int sid)
    //{
    //    GameObject gear = GetPanelChild(sid, "Panel_gear");
    //    foreach(Transform child in gear.transform)
    //    {
    //        child.gameObject.GetComponent<ParticleSystem>().Pause();
    //    }
    //}

    //public void PlayGear(int sid)
    //{
    //    foreach( int SID in  charOrderSidDic.Values)
    //    {

    //        if(SID != sid)
    //        {
    //            //glog.debug("PauseGear "+SID);
    //            PauseGear(SID);				
    //        }
    //    }

    //    GameObject gear = GetPanelChild(sid, "Panel_gear");
    //    foreach(Transform child in gear.transform)
    //    {
    //        child.gameObject.GetComponent<ParticleSystem>().Play();
    //    }
    //}

    public void StopOtherTurnAlarm(int sid)
    {
        foreach (int SID in charOrderSidDic.Values)
        {
            if (SID != sid)
            {
                //glog.debug("StopOtherTurnAlarm "+SID);
                StopTurnAlarm(SID, false);
            }
        }
    }

    public void StopAllTurnAlarmAndGear()
    {
        foreach (int SID in charOrderSidDic.Values)
        {
            StopTurnAlarm(SID, true);
            //PauseGear(SID);
        }
    }


    public void StopTurnAlarm(int sid, bool bClear)
    {
        if (!sidPanelDic.ContainsKey(sid))
            return;
        //GameObject fx = HudManager.Instance.GetPanelChild(sid, "FX");
        //if(fx==null)
        //    return;
        //ParticleSystem ps = fx.transform.FindChild("FX_circle").GetComponent<ParticleSystem>();
        //ps.Stop ();
        //if(bClear)
        //    ps.Clear();

       // SetTurnTimeCount(sid, false);
    }


    public GameObject GetCharPanel(int sid)
    {
        return sidPanelDic[sid];
    }

    public void SetCharInfo(int sid)
    {
        charInfoDic.Add(sid, new CharInfo());
    }

    public int GetMyMP()
    {

        int mySid = BoardManager.Instance.mySID;
        glog.debug("my mp = " + charInfoDic[mySid].mp);
        return charInfoDic[mySid].mp;
    }

    public int CurHP(int sid)
    {
        return charInfoDic[sid].hp;
    }

    public void ChangeHPBar(int sid, int change, bool instant)
    {
        if (sidPanelDic.ContainsKey(sid))
        {
            float fillAmount = (float)charInfoDic[sid].hp / (float)charInfoDic[sid].maxHp;
            glog.debug(sid + "  hp fillAmount = " + fillAmount + "  " + charInfoDic[sid].hp + "  " + charInfoDic[sid].maxHp); // 0.76 is lowest
            //fillAmount = 0.76f + 0.24f * fillAmount;
            glog.debug("finale fillamoust  " + fillAmount);
            //GetPanelGearChild(sid,"gage_HP_yellow").GetComponent<UISprite>().fillAmount = fillAmount;

            CharacterPanel char_panel = GetCharacterPanel(sid);

            if (instant)
            {
                char_panel.m_HP.fillAmount = fillAmount;
                char_panel.m_HP_Red.fillAmount = fillAmount;                
            }
            {
                if (change > 0)
                {
                    char_panel.m_HP.GetComponent<ChangeGauge>().SetGauge((float)charInfoDic[sid].hp, (float)charInfoDic[sid].maxHp, 0);
                    char_panel.m_HP_Red.GetComponent<ChangeGauge>().SetGauge((float)charInfoDic[sid].hp, (float)charInfoDic[sid].maxHp, 0);
                }
                else
                {
                    char_panel.m_HP.fillAmount = fillAmount;
                    char_panel.m_HP_Red.GetComponent<ChangeGauge>().SetGauge((float)charInfoDic[sid].hp, (float)charInfoDic[sid].maxHp, 0.5f);
                }
            }
            //		GetPanelChild(sid,"Hp").GetComponent<UISprite>().fillAmount = fillAmount;	
        }
    }

    public void SetMaxHP(int sid, int index, int maxhp)
    {
        charInfoDic[sid].maxHp = maxhp;
    }

    public void SetHP(int sid, int index, int hp)
    {
        charInfoDic[sid].hp = hp;
        ChangeHPBar(sid, 0, true);
    }


    public void SetMaxMP(int sid, int _maxmp)
    {
        charInfoDic[sid].maxMp = _maxmp;
    }

	public void SetMainCharMP(int sid, int mp)
	{
		SetMainCharMP(sid, mp , false);
	}

    public void SetMainCharMP(int sid, int mp, bool instantChange)
    {
        charInfoDic[sid].mp = mp;
        if (sidPanelDic.ContainsKey(sid))
        {
            //float fillAmount = mp/(float)charInfoDic[sid].maxMp;
            //fillAmount = 0.76f + 0.24f * fillAmount;
            //StartCoroutine( ChangeMPGage( GetPanelGearChild(sid,"gage_mp").GetComponent<UISprite>(), fillAmount) );
            //GetPanelGearChild(sid,"gage_mp").GetComponent<UISprite>().fillAmount = fillAmount;

            //GetPanelGearChild(sid,"gage_mp").GetComponent<ChangeGauge>().SetGauge((float)mp , (float)charInfoDic[sid].maxMp,0 );
			
            
            GetCharacterPanel(sid).m_MP.GetComponent<ChangeGauge>().SetGaugeFix(mp, instantChange);           

            UIManager.Instance.UpdateSkillPressBar(mp);

            //		GetPanelChild(sid,"MpLabel").GetComponent<UILabel>().text = mp.ToString();
        }
    }

    public void IncreaseMainCharMP(int sid, int addMp)
    {
        glog.debug(sid + "  IncreaseMainCharMP   cur=" + charInfoDic[sid].mp + "   add=" + addMp);
        SetMainCharMP(sid, charInfoDic[sid].mp + addMp);
    }

    public bool IsMaxMP(int sid)
    {
        if (charInfoDic[sid].mp == charInfoDic[sid].maxMp)
            return true;
        return false;
    }


    //	IEnumerator ChangeMPGage( UISprite gage_sprite, float finalFillAmount)
    //	{
    //		float gap = finalFillAmount - gage_sprite.fillAmount;
    //		if(gap>0)
    //		{
    //			while( gage_sprite.fillAmount < finalFillAmount)
    //			{
    //				glog.debug("fillamount "+gage_sprite.fillAmount+ "   gap="+gap);
    //				gage_sprite.fillAmount = gage_sprite.fillAmount + gap*Time.deltaTime;
    //				yield return null;
    //			}
    //		}
    //		else if(gap<0)
    //		{
    //			while( gage_sprite.fillAmount > finalFillAmount)
    //			{
    //				gage_sprite.fillAmount = gage_sprite.fillAmount + gap*Time.deltaTime;
    //				yield return null;
    //			}			
    //		}
    //		gage_sprite.fillAmount = finalFillAmount;
    //	}

    void MakeLiveUnit(int sid)
    {
        if (sidPanelDic.ContainsKey(sid))
        {
            //		GetPanelCharChild(sid,"Char").GetComponent<UISprite>().depth = 1;
            //		GetPanelChild(sid,"Hp").GetComponent<UISprite>().fillAmount = 1.0f;
            charInfoDic[sid].isDead = false;
        }
    }

    //public GameObject GetPanelChild(int sid, string name)
    //{
    //    if (!sidPanelDic.ContainsKey(sid))
    //        return null;

    //    return sidPanelDic[sid].transform.FindChild(name).gameObject;
    //}

    public CharacterPanel GetCharacterPanel(int sid)
    {
        if (!sidCharacterPanelDic.ContainsKey(sid))
            return null;

        return sidCharacterPanelDic[sid];
    }

	public void StartGageAni(int sid, float totalSeconds)
	{
		if (!sidCharacterPanelDic.ContainsKey(sid))
			return;
		sidCharacterPanelDic[sid].StartGageAni(totalSeconds);
	}

	public void StopGageAni(int sid)
	{
		if (!sidCharacterPanelDic.ContainsKey(sid))
			return;
		sidCharacterPanelDic[sid].StopGageAni();
	}

    public void HealUnitEffect(int sid, int hpChange)
    {
        if (!sidPanelDic.ContainsKey(sid))
            return;

        CharacterPanel char_panel = GetCharacterPanel(sid);

        Vector3 charPos = char_panel.m_Char.transform.localPosition;
        GameObject effGo = EffectManager.Instance.NGUICreateEffectZ(7, sidPanelDic[sid], charPos);
        Destroy(effGo, 3.0f);

        GameObject hpChangeLabel = NGUITools.AddChild(char_panel.m_Panel_char, hpChangePrefab);
        
        if (sidPanelDic[sid].transform.localScale.x < 0)
        {
            Vector3 scaleMod = hpChangeLabel.transform.localScale;
            scaleMod.x = -scaleMod.x;
            hpChangeLabel.transform.localScale = scaleMod;
        }
        //hpChangeLabel.transform.localRotation = sidPanelDic[sid].transform.localRotation;
        //charPos.z = hpChangePrefab.transform.position.z;
        //if(hpChangeLabel.transform.localRotation.y != 0)
        //	charPos.z = -charPos.z;
        //hpChangeLabel.transform.localPosition = charPos;
        //hpChangeLabel.transform.localScale = hpChangePrefab.transform.localScale;
        charPos.y += 25;
        hpChangeLabel.transform.localPosition = charPos;

        UILabel lbl = hpChangeLabel.GetComponent<UILabel>();
        lbl.depth = 10;
        lbl.text = hpChange.ToString();
        lbl.color = new Color(10 / 255.0f, 234 / 255.0f, 68 / 255.0f, 0.7f);
        StartCoroutine(HealDamageNumFadeOut(lbl));
        ChangeFace(sid, true);
    }

    public void DamageUnitEffect(int sid, int hpChange)
    {
        if (!sidPanelDic.ContainsKey(sid))
            return;

        CharacterPanel char_panel = GetCharacterPanel(sid);

        Vector3 charPos = char_panel.m_Char.transform.localPosition;
        GameObject effGo = EffectManager.Instance.NGUICreateEffectZ(6, sidPanelDic[sid], charPos);
        Destroy(effGo, 3.0f);

        BoardManager.Instance.RestartFSM(char_panel.m_Char.GetComponent<PlayMakerFSM>());

        GameObject hpChangeLabel = NGUITools.AddChild(char_panel.m_Panel_char, hpChangePrefab);
        if (sidPanelDic[sid].transform.localScale.x < 0)
        {
            Vector3 scaleMod = hpChangeLabel.transform.localScale;
            scaleMod.x = -scaleMod.x;
            hpChangeLabel.transform.localScale = scaleMod;
        }
        //hpChangeLabel.transform.localRotation = sidPanelDic[sid].transform.localRotation;
        //charPos.z = hpChangePrefab.transform.position.z;
        //if(hpChangeLabel.transform.localRotation.y != 0)
        //	charPos.z = -charPos.z;		
        //hpChangeLabel.transform.localPosition = charPos;

        //hpChangeLabel.transform.localScale = hpChangePrefab.transform.localScale;
        charPos.y += 25;
        hpChangeLabel.transform.localPosition = charPos;
        hpChangeLabel.GetComponent<UILabel>().depth = 10;

        if (hpChange < 0)
            hpChange = -hpChange;
        UILabel lbl = hpChangeLabel.GetComponent<UILabel>();
        lbl.depth = 10;
        lbl.text = hpChange.ToString();
        lbl.color = new Color(253 / 255.0f, 34 / 255.0f, 34 / 255.0f, 0.7f);
        StartCoroutine(HealDamageNumFadeOut(lbl));
        ChangeFace(sid, false);
    }

    IEnumerator HealDamageNumFadeOut(UILabel lbl)
    {
        yield return new WaitForSeconds(0.2f);
        if (lbl.gameObject == null)
            yield break;
        Vector3 newPos = lbl.gameObject.transform.localPosition;
        newPos.y += 20;
        iTween.MoveTo(lbl.gameObject, iTween.Hash("time", 1.2f, "position", newPos, "islocal", true));

        yield return new WaitForSeconds(0.4f);
        float alpha = lbl.color.a;
        Color original = lbl.color;

        while (alpha > 0)
        {
            //glog.debug("************ pos="+lbl.gameObject.transform.localPosition);
            alpha -= 2 * Time.deltaTime;
            if (alpha < 0)
                alpha = 0;
            lbl.color = new Color(original.r, original.g, original.b, alpha);
            yield return null;
        }
        Destroy(lbl.gameObject);
    }

    public bool SetChangedHP(int sid, int index, int beforeHp, int deltaHp)
    {
        if (deltaHp != 0)
        {
            CharInfo charInfo = charInfoDic[sid];
            if (charInfo.hp != beforeHp)
            {
                Debug.LogError("client hp differ sever.  " + charInfo.hp + "  " + beforeHp);

            }
            if (sidPanelDic.ContainsKey(sid))
            {
                glog.debug(sid + " SHOWING unit clienthp=" + charInfo.hp + "  beforehp=" + beforeHp + " deltahp=" + deltaHp + "  max=" + charInfo.maxHp);
                int final_hp = beforeHp + deltaHp;
                if (final_hp < 0)
                    final_hp = 0;
                if (final_hp > charInfo.maxHp)
                    final_hp = charInfo.maxHp;
                int valid_delta_hp = final_hp - beforeHp;
                if (valid_delta_hp != deltaHp)
                    glog.debug("recalculated deltahp=" + valid_delta_hp);
                if (valid_delta_hp != 0)
                {
                    charInfo.hpChange = valid_delta_hp;
                    charInfo.isShowHPChageEffect = true;
                    charInfo.hpToBe = final_hp;
                    return true;
                }
            }
            else
            {
                glog.debug("other unit client hp=" + charInfo.hp + "  beforehp=" + beforeHp + " delta=" + deltaHp + "  max=" + charInfo.maxHp);
                int final_hp = beforeHp + deltaHp;
                if (final_hp < 0)
                    final_hp = 0;
                if (final_hp > charInfo.maxHp)
                    final_hp = charInfo.maxHp;

                if (charInfo.hp > 0 && final_hp == 0)
                    charInfo.isDead = true;
                charInfo.hp = final_hp;
                glog.debug("finalhp=" + final_hp);
            }
        }
        return false;

    }

    public void ShowHPEffect(BoardPerson person, bool isHpChangeFromBoard, bool isRebirth)
    {
        ShowHPEffect(person, isHpChangeFromBoard, isRebirth, false);
    }

    public void ShowHPEffect(BoardPerson person, bool isHpChangeFromBoard, bool isRebirth, bool isAvoidDeath)
    {
        int sid = person.SID;
        CharInfo charInfo = charInfoDic[sid];
        //bool isHPChangeEffectShown = false;
        //int nHPChangeType = 0;
        int hpChange = 0;
        //bool isRevive = false;

        if (charInfo.hpChange != 0)
        {
            if (charInfo.isShowHPChageEffect)
            {
                //isHPChangeEffectShown = true;
                charInfo.isShowHPChageEffect = false;
                if (charInfo.hpChange > 0)
                {
                    hpChange = charInfo.hpChange;
                    //nHPChangeType = 1;

                    if (charInfo.hp <= 0)
                    {
                        MakeLiveUnit(sid);
                        //isRevive = true;
                    }
                    HealUnitEffect(sid, charInfo.hpChange);

                    glog.debug("isHPChangeEffectShown   heal");


                    if (!isRebirth)
                    {
                        HudManager.Instance.ShowAIEmotionChat(person.SID, "skill_good");
                        if (isAvoidDeath)
                            EffectManager.Instance.PlayEffect_AvoidDeath(person);
                        else
                        {
                            //EffectManager.Instance.PlayEffectParent(3, person.transform);
                            //EffectManager.Instance.DisableParticle(3, 3.0f);
                            EffectManager.Instance.PlayEffect_Heal(person);
                        }
                        SoundManager.Instance.PlaySound(ESound.Skill_Heal);
                    }
                    else
                    {
                        HudManager.Instance.ShowAIEmotionChat(person.SID, "resurrect");
                        SoundManager.Instance.PlaySound(23);
                    }


                    HitDamageNum damageNum = ObjectPool.Spawn(hpDamageNumPrefab) as HitDamageNum;

                    GameObject numGo = damageNum.gameObject;
                    numGo.transform.parent = person.transform;
                    numGo.transform.localPosition = hpDamageNumPrefab.transform.position;
                    numGo.transform.localScale = hpDamageNumPrefab.transform.localScale;
                    numGo.GetComponent<UILabel>().text = hpHealText.Replace("{0}", hpChange.ToString());
                    numGo.GetComponent<UILabel>().color = new Color(79 / 255.0f, 178 / 255.0f, 56 / 255.0f, 1);
                    StartCoroutine(CoObjectPoolRecycle(damageNum, 1.0f));

                }
                else
                {
                    hpChange = -charInfo.hpChange;
                    //nHPChangeType = 2;
                    DamageUnitEffect(sid, charInfo.hpChange);

                    glog.debug("isHPChangeEffectShown   damage   " + isHpChangeFromBoard);

                    if (isHpChangeFromBoard)
                    {
                        EffectManager.Instance.PlayEffect_Debuf(person);
                        HudManager.Instance.ShowAIEmotionChat(person.SID, "skill_bad");
                        SoundManager.Instance.PlaySound(ESound.Tile_Debuff);
                    }
                    else
                    {

                    }

                    HitDamageNum damageNum = ObjectPool.Spawn(hpDamageNumPrefab) as HitDamageNum;
                    GameObject numGo = damageNum.gameObject;
                    numGo.transform.parent = person.transform;
                    numGo.transform.localPosition = hpDamageNumPrefab.transform.position;
                    numGo.transform.localScale = hpDamageNumPrefab.transform.localScale;

                    numGo.GetComponent<UILabel>().text = hpDamageText.Replace("{0}", hpChange.ToString());
                    numGo.GetComponent<UILabel>().color = new Color(219 / 255.0f, 106 / 255.0f, 19 / 255.0f, 1);
                    StartCoroutine(CoObjectPoolRecycle(damageNum, 1.0f));
                }
            }

            charInfo.hp = charInfo.hpToBe;//charInfo.hp + charInfo.hpChange;
            if (charInfo.hp < 0)
                charInfo.hp = 0;
            if (charInfo.hp > charInfo.maxHp)
                charInfo.hp = charInfo.maxHp;

            ChangeHPBar(sid, charInfo.hpChange, false);

            charInfo.hpChange = 0;
        }
    }

    IEnumerator CoObjectPoolRecycle(HitDamageNum damageNum, float delay)
    {
        yield return new WaitForSeconds(delay);
        ObjectPool.Recycle(damageNum);
    }

    public void AddMpChangeInfo(int ServerID, BoardPerson person, MPRegenType reason, int before, int delta, int after, int boardId)
    {
        foreach (MPChangeInfo info in mpChangeInfo)
        {
            if (info.isApplied)
            {
                info.Init(ServerID, person, reason, before, delta, after, boardId);
                return;
            }
        }
        mpChangeInfo.Add(new MPChangeInfo(ServerID, person, reason, before, delta, after, boardId));
    }

    public void ShowMPChangeEffect_Instant()
    {
        foreach (MPChangeInfo info in mpChangeInfo)
        {
            if (!info.isApplied)
            {
                if (info.reason == MPRegenType.USE || info.reason == MPRegenType.REGEN_BY_TURN || info.reason == MPRegenType.SKILL_EFFECT)
                {
                    info.isApplied = true;
                    HudManager.Instance.SetMainCharMP(info.sid, info.after);

					if (info.reason == MPRegenType.SKILL_EFFECT || info.reason == MPRegenType.REGEN_BY_TURN)
                    {
                        if (info.delta > 0)
                        {
                            EffectManager.Instance.PlayEffect_MPRegen(info.person);
							if(info.reason == MPRegenType.SKILL_EFFECT) {
                            	HudManager.Instance.ShowAIEmotionChat(info.sid, "skill_good");
                            	HudManager.Instance.ChangeFace(info.sid, true);
							}
                        }
                        else
                        {
                            HudManager.Instance.ShowAIEmotionChat(info.sid, "skill_bad");
                            HudManager.Instance.ChangeFace(info.sid, false);
                        }
                    }
                }
            }
        }

        if (!BattleManager.Instance.bCombatHappened)
            ShowMPChangeEffect(MPRegenType.UNIT_SKILL_EFFECT);
    }

    public void ShowMPChangeEffect_AfterMove()
    {
        ShowMPChangeEffect(MPRegenType.BOARD_EFFECT);
        ShowMPChangeEffect(MPRegenType.CASE_MP_RECOVER_BOARD_EFFECT);
    }

    public void ShowMPChangeEffect_PassingMove(int bid)
    {
        ShowMPChangeEffect(MPRegenType.PASS_BOARD_EFFECT, bid);
        ShowMPChangeEffect(MPRegenType.PASS_CASE_MP_RECOVER_BOARD_EFFECT, bid);
    }

    public void ShowMPChangeEffect_PassingLap()
    {
        ShowMPChangeEffect(MPRegenType.PASS_THE_START_IN_LAP);
    }

    public void ShowMPChangeEffect(MPRegenType reason)
    {
        ShowMPChangeEffect(reason, 0);
    }

    public void ShowMPChangeEffect(MPRegenType reason, int bid)
    {
        foreach (MPChangeInfo info in mpChangeInfo)
        {
            if (!info.isApplied)
            {
                if (info.reason == reason)
                {
                    if (bid == 0 || bid == info.boardId)
                    {
                        info.isApplied = true;
                        HudManager.Instance.SetMainCharMP(info.sid, info.after);
                        if (info.delta > 0)
                        {
                            EffectManager.Instance.PlayEffect_MPRegen(info.person);
                            HudManager.Instance.ShowAIEmotionChat(info.sid, "skill_good");
                            HudManager.Instance.ChangeFace(info.sid, true);
                        }
                        else if (info.delta < 0)
                        {
                            HudManager.Instance.ShowAIEmotionChat(info.sid, "skill_bad");
                            HudManager.Instance.ChangeFace(info.sid, false);
                        }
                    }
                }
            }
        }
    }

    public void AddHpChangeInfo(int ServerID, BoardPerson person, HPModReason reason, int before_hp, int deltahp, int AfterHP, int boardId)
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (info.isApplied)
            {
                info.Init(ServerID, person, reason, before_hp, deltahp, AfterHP, boardId);
                return;
            }
        }
        hpChangeInfo.Add(new HPChangeInfo(ServerID, person, reason, before_hp, deltahp, AfterHP, boardId));
    }

    public void ShowHPChangeEffect()
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied)
            {
                info.isApplied = true;
                SetChangedHP(info.sid, 0, info.before, info.delta);
                ShowHPEffect(info.person, true, false);
            }
        }
    }

    public void ShowHPChangeEffect_BySkill()
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied)
            {
                if (info.reason == HPModReason.SKILL_EFFECT || (info.reason == HPModReason.UNIT_SKILL_EFFECT && !BattleManager.Instance.bCombatHappened))
                {
                    info.isApplied = true;
                    SetChangedHP(info.sid, 0, info.before, info.delta);
                    bool isRebirth = false;
                    if (info.before == 0 && info.delta > 0)
                        isRebirth = true;
                    ShowHPEffect(info.person, false, isRebirth);
                }
            }
        }
    }

    public void ShowHPChangeEffect_AfterMove()
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied && info.reason == HPModReason.BOARD_EFFECT)
            {
                info.isApplied = true;
                SetChangedHP(info.sid, 0, info.before, info.delta);
                ShowHPEffect(info.person, true, false);
            }
        }
    }

    public void ShowHPChangeEffect_Passing(int bid)
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied && info.reason == HPModReason.PASS_BOARD_EFFECT && info.boardId == bid)
            {
                info.isApplied = true;
                SetChangedHP(info.sid, 0, info.before, info.delta);
                ShowHPEffect(info.person, true, false);
            }
        }
    }

    public void ShowHPChangeEffect_AfterBattle()
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied && info.IsBattleReason())
            {
                info.isApplied = true;
                SetChangedHP(info.sid, 0, info.before, info.delta);
                ShowHPEffect(info.person, false, false);
            }
        }
    }

    public void ShowHPChangeEffect_AfterBattleCheckAvoidDeath()
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied && info.IsAvoidDeath())
            {
                info.isApplied = true;
                SetChangedHP(info.sid, 0, info.before, info.delta);
                ShowHPEffect(info.person, false, false, true);
            }
        }
    }

    public void ShowHPChangeEffect_AfterBattleByCard()
    {
        foreach (HPChangeInfo info in hpChangeInfo)
        {
            if (!info.isApplied && info.reason == HPModReason.UNIT_SKILL_EFFECT)
            {
                info.isApplied = true;
                SetChangedHP(info.sid, 0, info.before, info.delta);
                ShowHPEffect(info.person, false, false);
            }
        }
    }


    public void ShowUserEmotionChat(int sid, int emoticonId)
    {
        GetCharPanel(sid).GetComponent<CharacterPanel>().m_EmoticonImage.spriteName = string.Format("icon_emoticon_{0:00}", emoticonId);

        GetCharPanel(sid).GetComponent<CharacterPanel>().m_EmoticonBoxObj.SetActive(true);

        SoundManager.Instance.PlayEmoticonVoice(StageManagerWrapper.GetBoardPerson(sid).charID, emoticonId);

        StartCoroutine("Co_HideEmoticonBoxs", sid);
    }

    public void ShowAIEmotionChat(int sid, string emotionType)
    {
        if (StageManagerWrapper.GetBoardPerson(sid) != null && StageManagerWrapper.GetBoardPerson(sid).pawnType != GAME_PAWN_TYPE.AI)
            return;
        if (!sidPanelDic.ContainsKey(sid))
            return;
        Debug.Log(sid + " ShowAIEmotionChat  " + emotionType);
        //GetCharPanel(sid).GetComponent<CharacterPanel>()...
        int presetId = StageManagerWrapper.GetBoardPerson(sid).AIPresetId;
        Debug.Log("presetId : " + presetId);
        CUnitPresetData presetData = CUnitPresetDataManager.Instance.GetPresetData(presetId);

        if (presetData == null)
        {
            Debug.LogError("presertData is NULL");
        }
        else
        {
            string emotionDataName = CAIEmotionDataManager.Instance.GetAIEmotionData(presetData.emotion_type, emotionType);
            Debug.Log(emotionDataName);
            CEmotionData emotionData = CEmotionDataManager.Instance.GetEmotionData(emotionDataName);

            if (emotionData != null)
            {
                SoundManager.Instance.PlayEmoticonVoice(StageManagerWrapper.GetBoardPerson(sid).charID, emotionData.id);
                GetCharPanel(sid).GetComponent<CharacterPanel>().m_EmoticonImage.spriteName = emotionData.icon_name;
                GetCharPanel(sid).GetComponent<CharacterPanel>().m_EmoticonBoxObj.SetActive(true);
            }
            else
            {
                Debug.LogError("EmotionData is NULL!!");
            }

            StartCoroutine("Co_HideEmoticonBoxs", sid);
        }
    }

    IEnumerator Co_HideEmoticonBoxs(int sid)
    {
        yield return new WaitForSeconds(1f);

        GetCharPanel(sid).GetComponent<CharacterPanel>().m_EmoticonBoxObj.SetActive(false);
    }

    public Hashtable tempSkillListByGameOrder = new Hashtable();
    public void ShowAdditionalSkillFromGameOrder()
    {
        float delay = 0f;
        foreach (BoardPerson person in BoardManager.Instance.boardPersonPCList)
        {
            StartCoroutine(Co_ShowAdditionalSkillFromGameOrder(person, delay, 0, true));
            delay += 0.5f;
            //			GameObject tempObj = new GameObject();
            //			tempObj.transform.parent = UIManager.Instance.centerAnchor.transform;
            //			tempObj.layer = tempObj.transform.parent.gameObject.layer;
            //			tempObj.transform.localPosition = CardManager.Instance.FindScrPosCenter(person.transform.localPosition);
            //			tempObj.transform.localScale = Vector3.one;
            //			ChanceSkill chanceSkill = LTPrefabManager.InstantiateC(PrefabTypes.ChanceSkill, Vector3.zero, Quaternion.identity) as ChanceSkill;
            //			chanceSkill.transform.parent = tempObj.transform;
            //			chanceSkill.transform.localScale = Vector3.one;
            //			chanceSkill.orderIndex = person.order;
        }

    }

	IEnumerator Co_ShowAdditionalSkillFromGameOrder(BoardPerson person, float delay, int skillID, bool isAchieveAtStart)
    {
        yield return new WaitForSeconds(delay);

        GameObject tempObj = new GameObject();
        tempObj.name = "ChanceSkillParent";

        //ChanceSkill chanceSkill = LTPrefabManager.InstantiateC(PrefabTypes.ChanceSkill, Vector3.zero, Quaternion.identity) as ChanceSkill;
        ChanceSkill chanceSkill = ObjectPool.Spawn(chanceSkillPrefab) as ChanceSkill;
        //ChangeLayer( chanceSkill.gameObject, person.gameObject.layer);
        chanceSkill.person = person;

        Debug.LogWarning("heeso -------------------------------- skillID = " + skillID);

        if (skillID != 0)
        {
            chanceSkill.SetSkill(skillID);
            chanceSkill.gameObject.GetComponent<Animator>().enabled = true;
			if(!isAchieveAtStart)
            	chanceSkill.isAchieveInGame = true;
        }
        else
            chanceSkill.isAchieveInGame = false;

        chanceSkill.transform.parent = tempObj.transform;
        tempObj.transform.parent = person.transform;//UIManager.Instance.centerAnchor.transform;
        tempObj.transform.localPosition = Vector3.zero;
        tempObj.transform.localScale = new Vector3(0.002777778f, 0.002777778f, 0.002777778f);
        ChangeLayer(chanceSkill.gameObject, person.gameObject.layer);
        chanceSkill.transform.localPosition = Vector3.zero; //CardManager.Instance.FindScrPosCenter(person.transform.localPosition);
        chanceSkill.transform.localRotation = Quaternion.identity;
        chanceSkill.transform.localScale = Vector3.one;//chanceSkillPrefab.transform.localScale;
        chanceSkill.orderIndex = person.order;
    }

	public void AchieveTempSkill(BoardPerson person, int skillID, bool isAchieveAtStart)
	{
		glog.debug(String.Format("achieve temp skill {0}", skillID));
		StartCoroutine(Co_ShowAdditionalSkillFromGameOrder(person, 0, skillID, isAchieveAtStart));
	}

    public void AchieveTempSkill(BoardPerson person, int skillID)
    {
		AchieveTempSkill(person, skillID, false);
    }

    public void ChangeLayer(GameObject go, int layer)
    {
        go.layer = layer;
        foreach (Transform child in go.transform)
            ChangeLayer(child.gameObject, layer);
    }
}

